from django.shortcuts import render
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from .models import Product, ProductMainCategory, ProductSubCategory
import json

# 商品列表视图
def product_list(request):
    products = Product.objects.all()
    # 获取分类结构
    main_categories = ProductMainCategory.objects.all()
    category_dict = {}
    for main_cat in main_categories:
        sub_cats = main_cat.sub_categories.all()
        category_dict[main_cat.id] = {
            'name': main_cat.name,
            'sub_categories': {sub.id: sub.name for sub in sub_cats}
        }
    
    return render(request, 'product/list.html', {
        'products': products,
        'categories': category_dict,
        'title': '商品列表'
    })

# 商品详情视图
def product_detail(request, product_id):
    product = Product.objects.get(id=product_id)
    return render(request, 'product/detail.html', {
        'product': product,
        'title': product.name
    })

# 简单的测试视图
def test_view(request):
    return JsonResponse({'message': '商品模块测试页面'})

# 获取商品大类列表
@require_http_methods(['GET'])
def get_main_categories(request):
    try:
        categories = ProductMainCategory.objects.all().order_by('sort_order')
        data = [{
            'id': c.id,
            'name': c.name,
            'desc': c.desc if c.desc else ''
        } for c in categories]
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': data
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e)
        })

# 根据大类获取小类列表
@require_http_methods(['GET'])
def get_sub_categories(request):
    try:
        main_id = request.GET.get('main_id')
        if not main_id:
            return JsonResponse({
                'code': 400,
                'message': '缺少main_id参数'
            })
        
        sub_categories = ProductSubCategory.objects.filter(
            main_category_id=main_id
        ).order_by('sort_order')
        
        data = [{
            'id': sc.id,
            'name': sc.name,
            'desc': sc.desc if sc.desc else '',
            'main_category_id': sc.main_category.id
        } for sc in sub_categories]
        
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': data
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e)
        })
